package com.xhwl.data.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.dto.cent.sdata.*;
import com.xhwl.common.enums.LogOperationTypeEnum;
import com.xhwl.common.enums.ModuleTypeEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.config.BusinessType;
import com.xhwl.common.enums.config.InitializeEnum;
import com.xhwl.common.enums.config.InitializeRoleEnum;
import com.xhwl.common.enums.config.RoleTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.AbstractAccount;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.query.cent.sdata.PermissionQuery;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.common.query.cent.sdata.RoleQuery;
import com.xhwl.common.utils.CentDataVerifyUtil;
import com.xhwl.common.utils.DataVerifyUtil;
import com.xhwl.common.utils.ThreadLocalUtil;
import com.xhwl.data.dao.IPermissionDao;
import com.xhwl.data.dao.IProjectDao;
import com.xhwl.data.dao.IRoleDao;
import com.xhwl.data.dao.ISceneRoleDao;
import com.xhwl.data.mq.producer.RoleProducer;
import com.xhwl.data.pojo.RoleTypeQuery;
import com.xhwl.data.service.*;
import com.xhwl.data.util.EnumListUtil;
import com.xhwl.starter.log.LogTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @description:
 * @author:
 * @create: 2020-11-25
 **/
@Service
public class RoleServiceImpl extends ServiceImpl<IRoleDao, Role> implements IRoleService {
    private static final Logger log = LoggerFactory.getLogger(RoleServiceImpl.class);
    @Autowired
    IRoleDao roleDao;
    @Autowired
    IProjectDao projectDao;
    @Autowired
    ISceneRoleDao sceneRoleDao;
    @Autowired
    IAccountRoleService accountRoleService;
    @Autowired
    IAccountService accountService;
    @Autowired
    IRolePermissionService rolePermissionService;
    @Autowired
    IProjectService projectService;
    @Autowired
    IOrganizationService organizationService;
    @Autowired
    IPermissionService permissionService;
    @Autowired
    IEnterpriseService enterpriseService;
    @Autowired
    LogTemplate logTemplate;
    @Autowired
    RoleProducer roleProducer;

    @Autowired
    private IIndustryService industryService;

    @Autowired
    private IAppService appService;

    @Autowired
    private IPermissionDao permissionDao;

    @Autowired
    private IPermissionGroupService permissionGroupService;
    @Autowired
    private IPermissionAuthService permissionAuthService;

    /**
     * 判断账号的 管理员身份 （超管/企管/项管）
     *
     * @param accountId
     * @return
     */
    @Override
    public RoleTypeDTO getAccountRoleType(Integer accountId) {
        List<Integer> roleIdList = accountRoleService.findRoleIdByAccountId(accountId);
        if (CollectionUtils.isEmpty(roleIdList)) {
            log.error("accountId={} ,查询的角色list为空，传参有误", accountId);
            throw new DataException("该账号无关联任何角色，数据异常");
        }
        return getRoleTypeDTO(roleIdList);
    }

    /**
     * 批量判断账号的 管理员身份 （超管/企管/项管）
     *
     * @param accountIds
     * @return
     */
    @Override
    public Map<Integer, RoleTypeDTO> getAccountRoleTypeBatch(List<Integer> accountIds) {
        QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
        accountRoleQueryWrapper.select("role_id,account_id");
        accountRoleQueryWrapper.in("account_id", accountIds);
        List<AccountRole> accountRoleList = accountRoleService.list(accountRoleQueryWrapper);
        //批量统一查询角色数据使用
        Set<Integer> allRoleIdsSet = new HashSet<>();
        Map<Integer, Set<Integer>> accountRoleIdMap = new HashMap<>();
        for (AccountRole accountRole : accountRoleList) {
            Integer accountId = accountRole.getAccountId();
            Integer roleId = accountRole.getRoleId();
            if (!accountRoleIdMap.containsKey(accountId)) {
                Set<Integer> accountSet = new HashSet<>();
                accountSet.add(roleId);
                accountRoleIdMap.put(accountId, accountSet);
            } else {
                Set<Integer> accountSet = accountRoleIdMap.get(accountId);
                accountSet.add(roleId);
                accountRoleIdMap.put(accountId, accountSet);
            }
            allRoleIdsSet.add(roleId);
        }
        RoleQuery roleQuery = new RoleQuery();
        List<Integer> roleIds = new ArrayList<>(allRoleIdsSet);
        roleQuery.setIdList(new ArrayList<>(allRoleIdsSet));
        List<Integer> commonInitializedRoles = getCommonInitializedRoles(null);
        for (Integer roleId : commonInitializedRoles) {
            if (roleIds.contains(roleId)) {
                roleQuery.setNeedCommonInitialized(true);
            }
        }

        List<Role> roleAllList = getRoleList(null, roleQuery);
        Map<Integer, RoleTypeDTO> resultMap = new HashMap<>();
        for (Map.Entry<Integer, Set<Integer>> entry : accountRoleIdMap.entrySet()) {
            Integer accountId = entry.getKey();
            Set<Integer> roleIdsSet = entry.getValue();
            RoleTypeDTO roleTypeDTO = filterTopRoleTypeDTO(roleAllList, new ArrayList<>(roleIdsSet));
            resultMap.put(accountId, roleTypeDTO);
        }
        return resultMap;
    }

    /**
     * 根据角色id列表，筛选出当前的最高角色身份
     *
     * @param roleAllList
     * @param roleIdList
     * @return
     */
    public RoleTypeDTO filterTopRoleTypeDTO(List<Role> roleAllList, List<Integer> roleIdList) {
        Map<Integer, Role> roleAllInfoMap = roleAllList.stream().collect(Collectors.toMap(Role::getId, Function.identity()));
        List<Role> roleList = new ArrayList<>();
        for (Integer roleId : roleIdList) {
            if (null != roleAllInfoMap.get(roleId)) {
                roleList.add(roleAllInfoMap.get(roleId));
            }
        }
        if (CollectionUtils.isEmpty(roleList)) {
            //其他
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.OTHERS);
            return roleTypeDTO;
        }
        List<Role> superManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.SUPPER_MANAGER.code)).collect(Collectors.toList());
        //超级管理员
        if (!CollectionUtils.isEmpty(superManageList)) {
            List<Short> industryIdList = superManageList.stream().map(e -> e.getIndustryId()).collect(Collectors.toList());
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.SUPPER_MANAGER);
            roleTypeDTO.setIndustryIdList(industryIdList);
            return roleTypeDTO;
        }
        //运维管理员
        //List<Role> operateManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.OPERATE_MANAGER.code)).collect(Collectors.toList());
        List<Role> entManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.MANAGER.code)
                && role.getGrade().equals(BusinessType.ENTERPRISE.code)).collect(Collectors.toList());
        //企业管理员
        if (!CollectionUtils.isEmpty(entManageList)) {
            List<Integer> entIds = entManageList.stream().map(e -> e.getEnterpriseId()).collect(Collectors.toList());
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.ENT_MANAGER);
            roleTypeDTO.setEnterpriseIdList(entIds);
            return roleTypeDTO;
        }
        List<Role> proManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.MANAGER.code)
                && role.getGrade().equals(BusinessType.PROJECT.code)).collect(Collectors.toList());
        //项目管理员
        if (!CollectionUtils.isEmpty(proManageList)) {
            List<Integer> proIdList = proManageList.stream().map(r -> r.getProjectId()).collect(Collectors.toList());
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.PRO_MANAGER);
            roleTypeDTO.setProjectIdList(proIdList);
            return roleTypeDTO;
        }
        List<Role> commonList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.COMMON.code)).collect(Collectors.toList());
        //普通
        if (!CollectionUtils.isEmpty(commonList)) {
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.COMMON);
            return roleTypeDTO;
        }
        List<Role> guestList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.GUEST.code)).collect(Collectors.toList());
        //游客
        if (!CollectionUtils.isEmpty(guestList)) {
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.GUEST);
            return roleTypeDTO;
        }
        //其他
        RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
        roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.OTHERS);
        return roleTypeDTO;
    }


    /**
     * 批量新增初始化的内置普通角色
     *
     * @param roles
     */
    @Override
    public void initializeRoleBatch(List<Role> roles) {
        roleDao.initializeRoleBatch(roles);
    }

    /**
     * 根据账号id获取关联的角色
     *
     * @param accountId
     * @return
     */
    @Override
    public List<Role> getRoleListByAccountId(Integer accountId) {
        List<Integer> roleIdList = accountRoleService.findRoleIdByAccountId(accountId);
        if (roleIdList.isEmpty()) {
            return Collections.emptyList();
        }
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setIdList(roleIdList);
        List<Role> roleListDynamic = getRoleList(null, roleQuery);
        return roleListDynamic;
    }

    @Override
    public ResultJson isContainEstateRole(Integer accountId) {
        List<Role> roles = getRoleListByAccountId(accountId);
        Boolean isContain = false;
        // 当账号包含内置的管理员（1,2）或者不是内置的普通角色（0,3）时同步账号
        for (Role role : roles) {
            Boolean isInitialized = role.getIsInitialized();
            Integer roleType = role.getType();
            // 非内置、普通角色，true
            if (!isInitialized && RoleTypeEnum.COMMON.getCode() == roleType) {
                isContain = true;
                break;
            }
            // 内置、code为空、角色类型不为超级管理员，true
            if (isInitialized && null == role.getCode() && RoleTypeEnum.SUPPER_MANAGER.getCode() != roleType) {
                isContain = true;
                break;
            }
        }
//        for (Role role : roles) {
//            Boolean isInitialized = role.getIsInitialized();
//            if (!isInitialized) {
//                isContain = true;
//                break;
//            }
//            Integer roleType = role.getType();
//            if (RoleTypeEnum.COMMON.getCode() != roleType) {
//                isContain = true;
//                break;
//            }
//        }
        return ResultJson.success(isContain);
    }


    /**
     * 根据主键id 获取角色信息
     *
     * @param id
     * @return
     */
    @Override
    public Role getRoleById(Integer id) {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("id", id);
        roleQueryWrapper.eq("is_deleted", false);
        return roleDao.selectOne(roleQueryWrapper);
    }


    /**
     * 创建角色
     *
     * @param roleGrantDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson<Integer> createRole(RoleGrantDTO roleGrantDTO) {
        //通过orgId 转换出企业id 和 项目id
//        roleGrantDTO = roleEntProIdConvert(roleGrantDTO);
        //角色数据 格式校验
        roleDataVerify(roleGrantDTO);
        Role role = new Role();
        BeanUtils.copyProperties(roleGrantDTO, role);
        //角色 验重
        Boolean roleExistResult = roleExistChecking(roleGrantDTO);
        if (roleExistResult) {
            throw new BusinessException("角色名称重复,操作失败");
        }
        if (StringUtils.isNotEmpty(roleGrantDTO.getAppId())) {
            App app = appService.getByAppId(roleGrantDTO.getAppId());
            if (null == app) {
                throw new DataException("应用不存在");
            }
            role.setAppId(app.getId());
        }
        if(StringUtils.isEmpty(role.getCode())){
            role.setCode(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));
        }
        save(role);
        //插入 角色权限表
        rolePermissionService.createRolePermission(role.getId(), roleGrantDTO.getPermissionIds());
        //创建场景关联
        createRoleScene(role.getId(),roleGrantDTO.getSceneIds());
        //记录日志
        roleLogRecord(null, LogOperationTypeEnum.CREATE, "新增角色" + "【" + role.getName() + "】", roleGrantDTO);
        return ResultJson.success("操作成功", role.getId());
    }

    /**
     * 角色名验重
     *
     * @param roleGrantDTO
     * @return
     */
    @Override
    public ResultJson roleNameExistCheck(RoleGrantDTO roleGrantDTO) {
        if (null == roleGrantDTO.getOrganizationId()) {
            log.error("organizationId为空，无法进行角色名验重");
            throw new DataException("参数异常,操作失败");
        }
        //通过orgId 转换出企业id 和 项目id
        roleGrantDTO = roleEntProIdConvert(roleGrantDTO);
        Role role = new Role();
        BeanUtils.copyProperties(roleGrantDTO, role);
        //角色 验重
        Boolean roleExistResult = roleExistChecking(roleGrantDTO);
        if (roleExistResult) {
            return ResultJson.fail("角色名称重复,操作失败");
        }
        return ResultJson.success("验证通过");
    }

    @Override
    public ResultJson createRoleAdmin(Role role) {
        save(role);
        return ResultJson.success("操作成功");
    }

    @Override
    @Transactional
    public ResultJson createRoleAdminV2(RoleGrantDTO role, AdminAccount adminAccount) {
        Role role1 = new Role();
        BeanUtils.copyProperties(role, role1);
        String appId = role.getAppId();
        App app = appService.getByAppId(appId);
        if (null == app) {
            return ResultJson.fail("不存在的应用");
        }
        // 平台角色才有业态id
        if (role.getGrade() == 2 && null == role.getIndustryId()) {
            return ResultJson.fail("缺少平台参数");
        }
        if (roleExistChecking(role)) {
            return ResultJson.fail("角色重复");
        }
        role1.setAppId(app.getId());
        // 默认填充的参数
        if (StringUtils.isEmpty(role1.getCode())) {
            role1.setCode(UUID.randomUUID().toString().replace("-", ""));
        }
        if (null == role1.getGrade()) {
            // 平台角色
            role1.setGrade((short) 2);
        }
        if (null == role1.getType()) {
            // 普通角色
            role1.setType(RoleTypeEnum.COMMON.code);
        }
        if (null == role1.getLevel()) {
            role1.setLevel(1);
        }
        if (null == role1.getSortNum()) {
            role1.setSortNum(1);
        }
        if (null == role1.getParentId()) {
            role1.setParentId(0);
        }
        save(role1);
        List<Integer> permissionIds = role.getPermissionIds();
        if (!CollectionUtils.isEmpty(permissionIds)) {
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.select("id");
            permissionQueryWrapper.in("id", permissionIds);
            List<Permission> permissions = permissionDao.selectList(permissionQueryWrapper);
            if (!CollectionUtils.isEmpty(permissions)) {
                rolePermissionService.createRolePermission(role1.getId(), permissions.stream().map(i -> i.getId()).collect(Collectors.toList()));
            }
        }
        //创建场景关联
        createRoleScene(role1.getId(),role.getSceneIds());
        //刷新权限缓存
        permissionAuthService.refreshAppAuth(app.getId().toString());
        return ResultJson.success("角色保存成功");
    }


    @Override
    public ResultJson permissionBind(Integer id, List<Integer> permissionIds) {

        Role roleExist = getRoleById(id);
        if (Objects.isNull(roleExist)) {
            return ResultJson.fail("角色数据不存在");
        }
        Short industryId = roleExist.getIndustryId();
        if (CollectionUtils.isEmpty(permissionIds)) {
            return ResultJson.fail("缺少权限数据");
        }
        PermissionQuery permissionQuery = new PermissionQuery();
        permissionQuery.setIdList(permissionIds);
        List<Permission> permissionList = permissionService.getPermissionList(permissionQuery);
        if (CollectionUtils.isEmpty(permissionList)) {
            return ResultJson.fail("数据库中无当前权限数据");
        }
        List<Short> permissionIndustryList = permissionList.stream().map(Permission::getIndustryId).distinct().collect(Collectors.toList());
        if (1 != permissionIndustryList.size()) {
            log.info("传入角色的业态id={}，绑定的权限数据业态类型不匹对={}", industryId, permissionIndustryList.toString());
            return ResultJson.fail("绑定的权限数据业态类型不匹对");
        }
        Short industryIdDb = permissionIndustryList.get(0);
        if (!industryId.equals(industryIdDb)) {
            log.info("传入角色的业态id={}，绑定的权限数据业态类型不匹对={}", industryId, permissionIndustryList.toString());
            return ResultJson.fail("绑定的权限数据业态类型不匹对");
        }

        //先移除
        rolePermissionService.deleteRolePermission(Arrays.asList(id), null);
        //后新增关联数据
        rolePermissionService.createRolePermission(id, permissionIds);

        return ResultJson.success("操作成功");
    }

    /**
     * 更新角色
     *
     * @param operateAccount
     * @param roleGrantDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson updateRole(AbstractAccount operateAccount, RoleGrantDTO roleGrantDTO) {
        //修改
        Role roleExist = getRoleById(roleGrantDTO.getId());
        if (Objects.isNull(roleExist)) {
            throw new BusinessException("角色数据不存在");
        }
        if (StringUtils.isNotEmpty(roleGrantDTO.getName())) {
            CentDataVerifyUtil.roleNameVerify(roleGrantDTO.getName());
        }
        //获取当前登录操作账号的角色身份
        if (operateAccount instanceof Account) {
            if (null == roleGrantDTO.getEnterpriseId()) {
                log.info("企业信息不能为空,roleGrantDTO={}", roleGrantDTO.toString());
                throw new BusinessException("企业信息不能为空");
            }
            RoleTypeEnum operateRoleType = getAccountRoleType(operateAccount.getId()).getRoleTypeEnum();
            //修改角色时的权限范围检测
            Boolean checkResult = updateRoleCheck(operateRoleType, roleExist);
            if (!checkResult) {
                return ResultJson.fail("操作失败,权限不足");
            }
        }
        roleDataVerify(roleGrantDTO);
        //通过orgId 转换出企业id 和 项目id
//        roleGrantDTO = roleEntProIdConvert(roleGrantDTO);
        //角色 验重
        Boolean roleExistCheckingResult = roleExistChecking(roleGrantDTO);
        if (roleExistCheckingResult) {
            throw new BusinessException("角色名称重复,操作失败");
        }
        BeanUtils.copyProperties(roleGrantDTO, roleExist);
        updateById(roleExist);
        //超管不需要更新角色、权限关联
        if (!RoleTypeEnum.SUPPER_MANAGER.code.equals(roleGrantDTO.getType())) {
            rolePermissionService.createRolePermission(roleExist.getId(), roleGrantDTO.getPermissionIds());
        }

        // 检查权限组，移除不符合要求的项目
        permissionGroupHandler(roleExist.getId());
        //创建场景关联
        createRoleScene(roleGrantDTO.getId(),roleGrantDTO.getSceneIds());
        //记录日志
        roleLogRecord(operateAccount, LogOperationTypeEnum.UPDATE, "编辑角色" + "【" + roleExist.getName() + "】", roleGrantDTO);
        return ResultJson.success("操作成功");
    }


    /**
     * 移除在权限组里不合适的项目
     * @param roleId
     */
    private void permissionGroupHandler(Integer roleId){
        QueryWrapper<PermissionGroup> permissionGroupQueryWrapper = new QueryWrapper<>();
        permissionGroupQueryWrapper.like("role_ids", roleId);
        List<PermissionGroup> list = permissionGroupService.list(permissionGroupQueryWrapper);
        if(!org.apache.commons.collections4.CollectionUtils.isEmpty(list)){
            permissionGroupService.permissionGroupFilter(list.stream().map(i -> i.getId()).collect(Collectors.toList()));
        }
    }

    @Override
    public ResultJson updateByAdmin(Role role) {

        Role role1 = roleDao.selectById(role.getId());
        if (null == role1) {
            return ResultJson.fail("角色不存在");
        }
        log.info("运维平台正在修改角色 {} -> {}", role1, role);
        roleDao.updateById(role);
        return ResultJson.success();
    }


    /**
     * 通过角色内的orgId 转换出企业id 和 项目id
     *
     * @param roleGrantDTO
     * @return
     */
    public RoleGrantDTO roleEntProIdConvert(RoleGrantDTO roleGrantDTO) {

        Integer organizationId = roleGrantDTO.getOrganizationId();
        Organization organization = organizationService.getById(organizationId);
        if (Objects.isNull(organization)) {
            throw new DataException("不存在该组织,操作失败");
        }
        Integer type = organization.getType();
        //如果是企业级角色
        if (OrganizationTypeEnum.ENTERPRISE.id.intValue() == type) {
            roleGrantDTO.setEnterpriseId(organization.getEnterpriseId());
            roleGrantDTO.setGrade(BusinessType.ENTERPRISE.getCode());
            if (null != roleGrantDTO.getOperateAccountId()) {
                Integer operateAccountId = roleGrantDTO.getOperateAccountId();
                //获取当前登录操作账号的角色身份
                RoleTypeEnum operateRoleType = getAccountRoleType(operateAccountId).getRoleTypeEnum();
                if (!RoleTypeEnum.ENT_MANAGER.equals(operateRoleType)) {
                    if (!RoleTypeEnum.SUPPER_MANAGER.equals(operateRoleType)) {
                        log.info("检测到操作人无法操作 企业级角色 ，创建失败，操作人账号id={}", operateAccountId);
                        throw new BusinessException("操作失败");
                    }
                }
            }
        }
        //如果是项目级角色
        if (OrganizationTypeEnum.PROJECT.id.intValue() == type) {
            roleGrantDTO.setEnterpriseId(organization.getEnterpriseId());
            //根据orgId找出项目id
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("organization_id", organization.getId());
            projectQueryWrapper.eq("is_deleted", false);
            Project project = projectDao.selectOne(projectQueryWrapper);
            if (Objects.isNull(project)) {
                throw new DataException("不存在该组织id对应的项目,操作失败");
            }
            roleGrantDTO.setGrade(BusinessType.PROJECT.getCode());
            roleGrantDTO.setProjectId(project.getId());
            roleGrantDTO.setProName(project.getName());
            roleGrantDTO.setEnterpriseId(project.getEnterpriseId());
        }
        return roleGrantDTO;

    }

    /**
     * 删除角色 /关联关系
     *
     * @param roleId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson deleteRole(Account operateAccount, Integer roleId) {

        Role role = this.getById(roleId);
        if(null == role){
            return ResultJson.fail("不存在");
        }
        role.setIsDeleted(true);
        updateById(role);
        rolePermissionService.deleteRolePermission(Arrays.asList(roleId), null);

        Integer projectId = role.getProjectId();
        RoleGrantDTO grantDTO = new RoleGrantDTO();
        BeanUtils.copyProperties(role, grantDTO);
        if (null != role.getProjectId()) {
            Project project = projectService.findById(projectId);
            if (null != project) {
                grantDTO.setProName(project.getName());
            }
        }
        //记录日志
        roleLogRecord(operateAccount, LogOperationTypeEnum.DELETE, "删除角色" + "【" + role.getName() + "】", grantDTO);
        roleProducer.deletePush(JSON.toJSONString(role));
        return ResultJson.success();
    }

    /**
     * 角色类型选择器
     *
     * @return
     */
    @Override
    public ResultJson getRoleType() {
        List<RoleTypeEnum> business = RoleTypeEnum.getForType("business");
        if(CollectionUtils.isEmpty(business)){
            return ResultJson.success(Collections.emptyMap());
        }else{
            List<Map<String, Object>> result = new ArrayList<>(business.size());
            for (RoleTypeEnum roleTypeEnum : business) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", roleTypeEnum.getCode());
                map.put("name", roleTypeEnum.getName());
                result.add(map);
            }
            return ResultJson.success(result);
        }
    }

    @Override
    public List<Map<String, Object>> getRoleType(RoleTypeQuery roleTypeQuery) {
        List<RoleTypeEnum> list = new ArrayList<>();
        if(null != roleTypeQuery){
            if(!CollectionUtils.isEmpty(roleTypeQuery.getCodes())){
                list = Arrays.stream(RoleTypeEnum.values()).filter(i -> roleTypeQuery.getCodes().contains(i.code)).collect(Collectors.toList());
            }
            if(!CollectionUtils.isEmpty(roleTypeQuery.getTypes())){
                list = Arrays.stream(RoleTypeEnum.values()).filter(i -> roleTypeQuery.getTypes().contains(i.type)).collect(Collectors.toList());
            }
        }
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        List<Map<String, Object>> result = new ArrayList<>(list.size());
        for (RoleTypeEnum roleTypeEnum : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", roleTypeEnum.getCode());
            map.put("name", roleTypeEnum.getName());
            result.add(map);
        }
        return result;
    }


    public void dealPermissionCodes(RoleQuery roleQuery) {
        if (!CollectionUtils.isEmpty(roleQuery.getPermissionCodes())) {
            List<String> permissionCodes = roleQuery.getPermissionCodes();
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.select("id");
            if (!CollectionUtils.isEmpty(roleQuery.getIndustryIdList())) {
                permissionQueryWrapper.in("industry_id", roleQuery.getIndustryIdList());
            }
            permissionQueryWrapper.in("code", permissionCodes);
            List<Permission> permissions = permissionService.list(permissionQueryWrapper);
            if (!CollectionUtils.isEmpty(permissions)) {
                List<Integer> permissionIds = permissions.stream().map(e -> e.getId()).collect(Collectors.toList());
                QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
                rolePermissionQueryWrapper.select("role_id");
                rolePermissionQueryWrapper.in("permission_id", permissionIds);
                List<RolePermission> rolePermissions = rolePermissionService.list(rolePermissionQueryWrapper);
                if (!CollectionUtils.isEmpty(rolePermissions)) {
                    List<Integer> roleIds = rolePermissions.stream().map(e -> e.getRoleId()).collect(Collectors.toList());
                    Set<Integer> inRoleIdsSet = new HashSet<>();
                    if (!CollectionUtils.isEmpty(roleQuery.getIdList())) {
                        List<Integer> idList = roleQuery.getIdList();
                        inRoleIdsSet.addAll(idList);
                    }
                    inRoleIdsSet.addAll(roleIds);
                    List<Integer> inRoleIdsList = new ArrayList<>(inRoleIdsSet);
                    roleQuery.setIdList(inRoleIdsList);
                }
            }
        }
    }


    /**
     * 动态分页获取角色信息
     *
     * @param operateAccount
     * @param page
     * @param roleQuery
     * @return
     */
    @Override
    public Page<Role> getRolePageList(Account operateAccount, Page page, RoleQuery roleQuery) {

        if (null != roleQuery) {
            //处理内置角色相关条件逻辑
            dealCommonInitRoles(roleQuery);
            //处理超管角色相关条件逻辑
            dealSuperAdminRoles(roleQuery);
            //处理权限码相关条件逻辑
            dealPermissionCodes(roleQuery);
        }

        roleQuery = handleRequest(operateAccount, roleQuery);
        return roleDao.selectPage(page, handleParams(roleQuery));

    }


    /**
     * 查询出普通内置角色ids
     *
     * @return
     */
    @Override
    public List<Integer> getCommonInitializedRoles(List<Short> industryIdList) {
        List<Role> initializeRoles = getCommonInitRoleDetail(industryIdList);
        List<Integer> roleIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(initializeRoles)) {
            roleIds = initializeRoles.stream().map(e -> e.getId()).collect(Collectors.toList());
        }
        return roleIds;
    }


    @Override
    public List<Role> getCommonInitRoleDetail(List<Short> industryIdList) {
        //获取普通角色、内置类型  ，例如学生、教工、家长、后勤
        QueryWrapper<Role> initializeRoleQueryWrapper = new QueryWrapper<>();
        initializeRoleQueryWrapper.eq("type", RoleTypeEnum.COMMON.getCode());
        if (!CollectionUtils.isEmpty(industryIdList)) {
            initializeRoleQueryWrapper.in("industry_id", industryIdList);
        }
        initializeRoleQueryWrapper.eq("is_initialized", InitializeEnum.IS_INITIALIZE.getCode());
        List<Role> initializeRoles = list(initializeRoleQueryWrapper);

        return initializeRoles;
    }


    @Override
    public List<Integer> getSuperAdminRoles(List<Short> industryIdList) {

        List<Integer> roleIds = new ArrayList<>();
        QueryWrapper<Role> superAdminRoleQueryWrapper = new QueryWrapper<>();
        superAdminRoleQueryWrapper.eq("type", RoleTypeEnum.SUPPER_MANAGER.getCode());
        if (!CollectionUtils.isEmpty(industryIdList)) {
            superAdminRoleQueryWrapper.in("industry_id", industryIdList);
        }
        superAdminRoleQueryWrapper.eq("is_initialized", InitializeEnum.IS_INITIALIZE.getCode());
        List<Role> superAdminRoles = list(superAdminRoleQueryWrapper);
        if (!CollectionUtils.isEmpty(superAdminRoles)) {
            roleIds = superAdminRoles.stream().map(e -> e.getId()).collect(Collectors.toList());
        }
        return roleIds;
    }


    /**
     * 获取角色详情
     *
     * @param id
     * @return
     */
    @Override
    public RoleDetailDTO getDetail(Short industryId, Integer id) {
        RoleDetailDTO detailDTO = new RoleDetailDTO();
        Role role = getRoleById(id);
        if (Objects.isNull(role)) {
            throw new BusinessException("当前角色不存在");
        }
        BeanUtils.copyProperties(role, detailDTO);
        //项目id
        Integer projectId = role.getProjectId();
        //企业id
        Integer enterpriseId = role.getEnterpriseId();
        //组织架构名称填充
        RoleOrgStructureDTO roleOrgStructureData = getRoleOrgStructureData(Arrays.asList(role));
        Map<Integer, Integer> enterpriseOrganizationMap = new HashMap<>();
        Map<Integer, Integer> projectOrganizationMap = new HashMap<>();
        Map<Integer, String> organizationNameMap = new HashMap<>();
        if (Objects.nonNull(roleOrgStructureData)) {
            enterpriseOrganizationMap = roleOrgStructureData.getEnterpriseOrganizationMap();
            projectOrganizationMap = roleOrgStructureData.getProjectOrganizationMap();
            organizationNameMap = roleOrgStructureData.getOrganizationNameMap();
        }
        String orgStructureName = null;
        Integer orgId = null;
        if (null != projectId) {
            orgId = projectOrganizationMap.get(projectId);
            detailDTO.setProjectId(projectId);
            detailDTO.setGrade(BusinessType.PROJECT.getCode());
            detailDTO.setOrgStructureId(orgId);
        } else if (null != enterpriseId) {
            orgId = enterpriseOrganizationMap.get(enterpriseId);
            detailDTO.setOrgStructureId(orgId);
            detailDTO.setEnterpriseId(enterpriseId);
            detailDTO.setGrade(BusinessType.ENTERPRISE.getCode());
        }
        if (null != orgId) {
            orgStructureName = organizationNameMap.get(orgId);
        }
        //填充  该角色的组织架构全名
        detailDTO.setOrgStructureName(orgStructureName);
        //填充 角色类型名称
        if (null != detailDTO.getType()) {
            RoleTypeEnum roleTypeEnum = RoleTypeEnum.findRoleTypeEnum(detailDTO.getType());
            detailDTO.setTypeName(roleTypeEnum.getName());
        }
        //填充角色是否内置名称
        if (null != detailDTO.getIsInitialized()) {
            if (detailDTO.getIsInitialized()) {
                detailDTO.setIsInitializedName("内置角色");
            } else {
                detailDTO.setIsInitializedName("自定义角色");
            }
        }
        List<Permission> permissions = permissionService.getListByRoleId(null, id);
        if (!CollectionUtils.isEmpty(permissions)) {
            List<Integer> permissionIds = permissions.stream().map(e -> e.getId()).collect(Collectors.toList());
            detailDTO.setPermissionList(permissionIds);
        }
        return detailDTO;

    }


    /**
     * 修改角色 权限范围检测 （单个）
     *
     * @param operateRoleType 当前登录账号的角色身份
     * @param oRole           即将修改的角色信息
     * @return
     */
    @Override
    public Boolean updateRoleCheck(RoleTypeEnum operateRoleType, Role oRole) {
        //是否有角色管理权限
        if (!(RoleTypeEnum.SUPPER_MANAGER.equals(operateRoleType) || RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType) || RoleTypeEnum.ENT_MANAGER.equals(operateRoleType) || RoleTypeEnum.PRO_MANAGER.equals(operateRoleType) || RoleTypeEnum.COMMON.equals(operateRoleType))) {
            //   log.warn("当前操作员无角色管理权限");
            return false;
        }
        //业态后台 任何角色都不允许修改超级管理员角色
        if (RoleTypeEnum.SUPPER_MANAGER.code.equals(oRole.getType())) {
            //不能修改超级管理员角色
            return false;
        }
        //运维管理角色 无法修改 运维管理角色
        if (RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType)) {
            if (RoleTypeEnum.OPERATE_MANAGER.code.equals(oRole.getType())) {
                //运维角色不能修改运维角色
                return false;
            }
        }
        //企业管理员 无法修改 运维角色、企业管理员
        if (RoleTypeEnum.ENT_MANAGER.equals(operateRoleType)) {
            if (RoleTypeEnum.OPERATE_MANAGER.code.equals(oRole.getType())) {
                //企业管理员不能修改运维角色
                return false;
            }
            if (RoleTypeEnum.MANAGER.code.equals(oRole.getType()) && BusinessType.ENTERPRISE.code == oRole.getGrade()) {
                //企业管理员不能修改企业角色
                return false;
            }
        }
        //项目管理员 无法修改 项目管理员
        if (RoleTypeEnum.PRO_MANAGER.equals(operateRoleType) || RoleTypeEnum.COMMON.equals(operateRoleType)) {
            if (RoleTypeEnum.OPERATE_MANAGER.code.equals(oRole.getType())) {
                //项目管理员不能修改运维角色
                return false;
            }
            if (RoleTypeEnum.MANAGER.code.equals(oRole.getType()) && BusinessType.ENTERPRISE.code == oRole.getGrade()) {
                //项目管理员不能修改企业角色
                return false;
            }
            if (RoleTypeEnum.MANAGER.code.equals(oRole.getType()) && BusinessType.PROJECT.code == oRole.getGrade()) {
                //项目管理员不能修改项目角色
                return false;
            }
        }
        return true;
    }


    /**
     * 修改角色 权限范围检测 （批量）
     *
     * @param operateRoleType 当前登录账号的角色身份
     * @param roles           即将修改的角色信息
     * @return
     */
    @Override
    public Map<Integer, Boolean> updateRoleCheckBatch(RoleTypeEnum operateRoleType, List<Role> roles) {
        Map<Integer, Boolean> updateCheckResultMap = new HashMap<>();
        for (Role role : roles) {
            Integer roleId = role.getId();
            Integer roleType = role.getType();
            Short roleGrade = role.getGrade();
            //是否有角色管理权限
            if (!(RoleTypeEnum.SUPPER_MANAGER.equals(operateRoleType) || RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType) || RoleTypeEnum.ENT_MANAGER.equals(operateRoleType) || RoleTypeEnum.PRO_MANAGER.equals(operateRoleType) || RoleTypeEnum.COMMON.equals(operateRoleType))) {
                updateCheckResultMap.put(roleId, false);
                continue;
            }
            //业态后台 任何角色都不允许修改超级管理员角色
            if (RoleTypeEnum.SUPPER_MANAGER.code.equals(roleType)) {
                //不能修改超级管理员角色
                updateCheckResultMap.put(roleId, false);
                continue;
            }
            //运维管理角色 无法修改 运维管理角色
            if (RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType)) {
                if (RoleTypeEnum.OPERATE_MANAGER.code.equals(roleType)) {
                    //运维角色不能修改运维角色
                    updateCheckResultMap.put(roleId, false);
                    continue;
                }
            }
            //企业管理员 无法修改 运维角色、企业管理员
            if (RoleTypeEnum.ENT_MANAGER.equals(operateRoleType)) {
                if (RoleTypeEnum.OPERATE_MANAGER.code.equals(roleType)) {
                    //企业管理员不能修改运维角色
                    updateCheckResultMap.put(roleId, false);
                    continue;
                }
                if (RoleTypeEnum.MANAGER.code.equals(roleType) && BusinessType.ENTERPRISE.code == roleGrade) {
                    updateCheckResultMap.put(roleId, false);
                    continue;
                }
            }
            //项目管理员 无法修改 项目管理员
            if (RoleTypeEnum.PRO_MANAGER.equals(operateRoleType) || RoleTypeEnum.COMMON.equals(operateRoleType)) {
                if (RoleTypeEnum.OPERATE_MANAGER.code.equals(roleType)) {
                    //项目管理员不能修改运维角色
                    updateCheckResultMap.put(roleId, false);
                    continue;
                }
                if (RoleTypeEnum.MANAGER.code.equals(roleType) && BusinessType.ENTERPRISE.code == roleGrade) {
                    //项目管理员不能修改企业角色
                    updateCheckResultMap.put(roleId, false);
                    continue;
                }
                if (RoleTypeEnum.MANAGER.code.equals(roleType) && BusinessType.PROJECT.code == roleGrade) {
                    //项目管理员不能修改项目角色
                    updateCheckResultMap.put(roleId, false);
                    continue;
                }
            }
            //校验规则都通过，那么就是可以修改
            updateCheckResultMap.put(roleId, true);
        }

        return updateCheckResultMap;
    }


    /**
     * 删除角色 权限范围检测 （批量）
     *
     * @param operateRoleType 当前登录账号的角色身份
     * @param roles           即将修改的角色信息
     * @return
     */
    @Override
    public Map<Integer, Boolean> deleteRoleCheckBatch(RoleTypeEnum operateRoleType, List<Role> roles) {
        Map<Integer, Boolean> deleteCheckResultMap = new HashMap<>();
        for (Role role : roles) {
            Integer roleId = role.getId();
            Integer roleType = role.getType();
            Short roleGrade = role.getGrade();

            //是否有角色管理权限
            if (!(RoleTypeEnum.SUPPER_MANAGER.equals(operateRoleType) || RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType) || RoleTypeEnum.ENT_MANAGER.equals(operateRoleType) || RoleTypeEnum.PRO_MANAGER.equals(operateRoleType) || RoleTypeEnum.COMMON.equals(operateRoleType))) {
                deleteCheckResultMap.put(roleId, false);
                continue;
            }

            //业态后台 任何角色都不允许修改超级管理员角色
            if (RoleTypeEnum.SUPPER_MANAGER.code.equals(roleType)) {
                //不能修改超级管理员角色
                deleteCheckResultMap.put(roleId, false);
                continue;
            }
            //运维管理角色 无法修改 运维管理角色
            if (RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType)) {
                if (RoleTypeEnum.OPERATE_MANAGER.code.equals(roleType)) {
                    //运维角色不能修改运维角色
                    deleteCheckResultMap.put(roleId, false);
                    continue;
                }
            }
            //企业管理员 无法修改 运维角色、企业管理员
            if (RoleTypeEnum.ENT_MANAGER.equals(operateRoleType)) {
                if (RoleTypeEnum.OPERATE_MANAGER.code.equals(roleType)) {
                    //企业管理员不能修改运维角色
                    deleteCheckResultMap.put(roleId, false);
                    continue;
                }
                if (RoleTypeEnum.MANAGER.code.equals(roleType) && BusinessType.ENTERPRISE.code == roleGrade) {
                    deleteCheckResultMap.put(roleId, false);
                    continue;
                }
            }

            //项目管理员 无法修改 项目管理员
            if (RoleTypeEnum.PRO_MANAGER.equals(operateRoleType) || RoleTypeEnum.COMMON.equals(operateRoleType)) {
                if (RoleTypeEnum.OPERATE_MANAGER.code.equals(roleType)) {
                    //项目管理员不能修改运维角色
                    deleteCheckResultMap.put(roleId, false);
                    continue;
                }
                if (RoleTypeEnum.MANAGER.code.equals(roleType) && BusinessType.ENTERPRISE.code == roleGrade) {
                    //项目管理员不能修改企业角色
                    deleteCheckResultMap.put(roleId, false);
                    continue;
                }
                if (RoleTypeEnum.MANAGER.code.equals(roleType) && BusinessType.PROJECT.code == roleGrade) {
                    //项目管理员不能修改项目角色
                    deleteCheckResultMap.put(roleId, false);
                    continue;
                }
            }
            //校验规则都通过，那么就是可以修改
            deleteCheckResultMap.put(roleId, true);
        }

        return deleteCheckResultMap;
    }


    /**
     * 如果 返回false， 删除按钮不显示 。 这里需区分 内置角色不允许删除，采取删除按钮置灰。
     *
     * @param operateRoleType 当前登录账号的角色身份
     * @param oRole           即将修改的角色信息
     * @return
     */
    @Override
    public Boolean deleteRoleCheck(RoleTypeEnum operateRoleType, Role oRole) {

        //是否有角色管理权限
        if (!(RoleTypeEnum.SUPPER_MANAGER.equals(operateRoleType) || RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType) || RoleTypeEnum.ENT_MANAGER.equals(operateRoleType) || RoleTypeEnum.PRO_MANAGER.equals(operateRoleType))) {
            //log.warn("当前操作员无角色管理权限");
            return false;
        }
        //业态后台 任何角色都不允许修改超级管理员角色
        if (RoleTypeEnum.SUPPER_MANAGER.code.equals(oRole.getType())) {
            //不能删除超级管理员角色
            return false;
        }
        //运维管理角色 无法修改 运维管理角色
        if (RoleTypeEnum.OPERATE_MANAGER.equals(operateRoleType)) {
            if (RoleTypeEnum.OPERATE_MANAGER.code.equals(oRole.getType())) {
                //运维角色不能删除运维角色
                return false;
            }
        }
        //企业管理员 无法修改 运维角色、企业管理员
        if (RoleTypeEnum.ENT_MANAGER.equals(operateRoleType)) {
            if (RoleTypeEnum.OPERATE_MANAGER.code.equals(oRole.getType())) {
                //企业管理员不能删除运维角色
                return false;
            }
            if (RoleTypeEnum.MANAGER.code.equals(oRole.getType()) && BusinessType.ENTERPRISE.code == oRole.getGrade()) {
                //企业管理员不能删除企业角色
                return false;
            }
        }
        //项目管理员 无法修改 项目管理员
        if (RoleTypeEnum.PRO_MANAGER.equals(operateRoleType)) {
            if (RoleTypeEnum.OPERATE_MANAGER.code.equals(oRole.getType())) {
                //项目管理员不能删除运维角色
                return false;
            }
            if (RoleTypeEnum.MANAGER.code.equals(oRole.getType()) && BusinessType.ENTERPRISE.code == oRole.getGrade()) {
                //项目管理员不能删除企业角色
                return false;
            }
            if (RoleTypeEnum.MANAGER.code.equals(oRole.getType()) && BusinessType.PROJECT.code == oRole.getGrade()) {
                //项目管理员不能删除项目角色
                return false;
            }
        }
        return true;
    }


    /**
     * 获取当前项目关联的角色 （包括企业级角色、项目级角色 ，而业态级角色以及超管，选择性获取）
     *
     * @param industryId
     * @param projectIds
     * @param needCommonInitialized
     * @param needSuper
     * @return
     */
    @Override
    public List<RoleDetailDTO> getCurrentProjectRelatedList(Short industryId, List<Integer> projectIds, Boolean needCommonInitialized, Boolean needSuper) {

        List<Integer> typeList = new ArrayList<>();
        if (needCommonInitialized) {
            typeList.add(RoleTypeEnum.COMMON.getCode());
        }
        if (needSuper) {
            typeList.add(RoleTypeEnum.SUPPER_MANAGER.getCode());
        }
        RoleQuery roleQuery = new RoleQuery();
        if (!CollectionUtils.isEmpty(typeList)) {
            roleQuery.setGrade(BusinessType.INDUSTRY.getCode());
            roleQuery.setTypeList(typeList);
        }
        if (needCommonInitialized || needSuper) {
            roleQuery.setNeedInitialized(true);
        }
        if (!CollectionUtils.isEmpty(projectIds)) {
            roleQuery.setProjectIdList(projectIds);
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.setIds(projectIds);
            List<Project> projects = projectService.list(projectQuery, null);
            if (CollectionUtils.isEmpty(projects)) {
                log.info("项目id={},数据库内无数据", projectIds.toString());
                throw new DataException("项目数据异常");
            }
            List<Integer> enterpriseIds = projects.stream().map(Project::getEnterpriseId).collect(Collectors.toList());
            roleQuery.setEnterpriseIdList(enterpriseIds);
        }
        roleQuery.setIndustryIdList(Arrays.asList(industryId));

        List<RoleDetailDTO> resultList = roleDao.getCurrentProjectRelatedList(roleQuery);
        return resultList;
    }

    /**
     * 获取角色列表  与操作人的权限相关
     *
     * @param roleQuery
     * @return
     */
    @Override
    public List<Role> getRoleList(Account operateAccount, RoleQuery roleQuery) {
        if (null != roleQuery) {
            //处理内置角色相关条件逻辑
            dealCommonInitRoles(roleQuery);
            //处理权限码相关条件逻辑
            dealPermissionCodes(roleQuery);
        }
        roleQuery = handleRequest(operateAccount, roleQuery);
        return roleDao.selectList(handleParams(roleQuery));

    }

    public void dealSuperAdminRoles(RoleQuery roleQuery) {
        //如果不需要超管角色ids，就需要做排除 exclude设置
        if (null != roleQuery.getNeedSuperAdmin()) {
            if (!roleQuery.getNeedSuperAdmin()) {
                List<Integer> superAdminRoles = getSuperAdminRoles(roleQuery.getIndustryIdList());
                if (!CollectionUtils.isEmpty(superAdminRoles)) {
                    if (!CollectionUtils.isEmpty(roleQuery.getExcludeIdList())) {
                        //加上原本需要排除的角色ids
                        superAdminRoles.addAll(roleQuery.getExcludeIdList());
                    }
                    roleQuery.setExcludeIdList(superAdminRoles);
                }
            }
        }
    }


    public void dealCommonInitRoles(RoleQuery roleQuery) {
        //如果不需要普通内置角色ids，就需要做排除 exclude设置
        if (null != roleQuery.getNeedCommonInitialized()) {
            if (!roleQuery.getNeedCommonInitialized()) {
                List<Integer> commonInitializedRoles = getCommonInitializedRoles(null);
                if (!CollectionUtils.isEmpty(commonInitializedRoles)) {
                    if (!CollectionUtils.isEmpty(roleQuery.getExcludeIdList())) {
                        //加上原本需要排除的角色ids
                        commonInitializedRoles.addAll(roleQuery.getExcludeIdList());
                    }
                    roleQuery.setExcludeIdList(commonInitializedRoles);
                }
            } else {
                List<Integer> commonInitializedRoles = getCommonInitializedRoles(roleQuery.getIndustryIdList());
                roleQuery.setCommonInitialized(commonInitializedRoles);
            }
        }
    }


    /**
     * 查询各个角色 所关联的账号数
     *
     * @return
     */
    @Override
    public List<RoleDetailDTO> getAccountCountByRoleId(List<Integer> roleIds) {
        return accountRoleService.getCountByRoleId(roleIds);
    }

    @Override
    public Role getRole(RoleQuery roleQuery) {
        try {
            Role role = roleDao.selectOne(handleParams(roleQuery));
            return role;
        } catch (Exception e) {
            return null;
        }
    }

    private RoleQuery handleRequest(Account operateAccount, RoleQuery roleQuery) {
        if (null == operateAccount) {
            return roleQuery;
        }
        //当没有条件时，就是初始化查询
        if (Objects.isNull(roleQuery)) {

            RoleTypeDTO roleTypeDTO = getAccountRoleType(operateAccount.getId());
            RoleTypeEnum roleTypeEnum = roleTypeDTO.getRoleTypeEnum();
            roleQuery = new RoleQuery();
            //超管

            if (RoleTypeEnum.SUPPER_MANAGER.equals(roleTypeEnum)) {
                roleQuery.setIndustryIdList(roleTypeDTO.getIndustryIdList());
                return roleQuery;
            }
            // 运营人员
            if (RoleTypeEnum.OPERATE_MANAGER.equals(roleTypeEnum)) {
                if (!CollectionUtils.isEmpty(roleTypeDTO.getEnterpriseIdList())) {
                    roleQuery.setEnterpriseIdList(roleTypeDTO.getEnterpriseIdList());
                }
                if (!CollectionUtils.isEmpty(roleTypeDTO.getProjectIdList())) {
                    roleQuery.setProjectIdList(roleTypeDTO.getProjectIdList());
                }
                return roleQuery;
            }
            //企业管理员
            if (RoleTypeEnum.ENT_MANAGER.equals(roleTypeEnum)) {
                roleQuery.setEnterpriseIdList(roleTypeDTO.getEnterpriseIdList());
                return roleQuery;
            }
            //项目管理员
            if (RoleTypeEnum.PRO_MANAGER.equals(roleTypeEnum)) {
                roleQuery.setEnterpriseIdList(roleTypeDTO.getEnterpriseIdList());
                return roleQuery;
            }
//            throw new DataException("无管理项目权限");
        }

        return roleQuery;
    }


    /**
     * 权限数据/格式 校验
     *
     * @param roleGrantDTO
     */
    public void roleDataVerify(RoleGrantDTO roleGrantDTO) {
        if (String.valueOf(BusinessType.ENTERPRISE.code).equals(String.valueOf(roleGrantDTO.getGrade())) && null == roleGrantDTO.getEnterpriseId()) {
            throw new BusinessException("缺少企业信息");
        }
        //角色名校验
        if (StringUtils.isEmpty(roleGrantDTO.getName())) {
            log.info("角色名信息不能为空,roleGrantDTO={}", roleGrantDTO.toString());
            throw new BusinessException("角色名信息不能为空");
        }
        if (!DataVerifyUtil.isInRangeString(2, 24, roleGrantDTO.getName())) {
            throw new DataException("角色名只允许输入2-24个以内的字符");
        }
        //角色类型校验
        if (null == roleGrantDTO.getType()) {
            log.info("角色类型信息不能为空,roleGrantDTO={}", roleGrantDTO.toString());
            throw new BusinessException("角色类型信息不能为空");
        }
        //当角色等级为项目岗位等级时， 项目id不能为空
        if (String.valueOf(BusinessType.PROJECT.code).equals(String.valueOf(roleGrantDTO.getGrade()))) {
            if (null == roleGrantDTO.getProjectId()) {
                log.info("项目信息不能为空,roleGrantDTO={}", roleGrantDTO.toString());
                throw new BusinessException("项目信息不能为空");
            }
        }
        //权限list校验
        if (CollectionUtils.isEmpty(roleGrantDTO.getPermissionIds())) {
            log.info("权限信息不能为空,roleGrantDTO={}", roleGrantDTO.toString());
            throw new BusinessException("权限信息不能为空");
        }


    }

    /**
     * 角色验重
     *
     * @param roleGrantDTO
     * @return
     */
    @Override
    public Boolean roleExistChecking(RoleGrantDTO roleGrantDTO) {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        // 平台下验重
        if (String.valueOf(BusinessType.INDUSTRY.code).equals(String.valueOf(roleGrantDTO.getGrade()))) {
            roleQueryWrapper.select("id");
            if (null != roleGrantDTO.getId()) {
                roleQueryWrapper.ne("id", roleGrantDTO.getId());
            }
            if (null != roleGrantDTO.getGrade()) {
                roleQueryWrapper.eq("grade", roleGrantDTO.getGrade());
            }
            roleQueryWrapper.eq("industry_id", roleGrantDTO.getIndustryId());
            roleQueryWrapper.eq("name", roleGrantDTO.getName());
            roleQueryWrapper.eq("is_deleted", false);
            return null != roleDao.selectOne(roleQueryWrapper);
        } else if (String.valueOf(BusinessType.ENTERPRISE.code).equals(String.valueOf(roleGrantDTO.getGrade()))) { //同企业的通用角色不能重复定义
            roleQueryWrapper.select("id");
            if (null != roleGrantDTO.getId()) {
                roleQueryWrapper.ne("id", roleGrantDTO.getId());
            }
            roleQueryWrapper.eq("enterprise_id", roleGrantDTO.getEnterpriseId());
            roleQueryWrapper.eq("grade", roleGrantDTO.getGrade());
            roleQueryWrapper.eq("name", roleGrantDTO.getName());
            roleQueryWrapper.eq("is_deleted", false);
            return null != roleDao.selectOne(roleQueryWrapper);
        } else if (String.valueOf(BusinessType.PROJECT.code).equals(String.valueOf(roleGrantDTO.getGrade()))) { //同项目下的项目角色不能重复定义
            roleQueryWrapper.select("id");
            if (null != roleGrantDTO.getId()) {
                roleQueryWrapper.ne("id", roleGrantDTO.getId());
            }
            roleQueryWrapper.eq("enterprise_id", roleGrantDTO.getEnterpriseId());
            roleQueryWrapper.eq("project_id", roleGrantDTO.getProjectId());
            roleQueryWrapper.eq("grade", roleGrantDTO.getGrade());
            roleQueryWrapper.eq("name", roleGrantDTO.getName());
            roleQueryWrapper.eq("is_deleted", false);
            return null != roleDao.selectOne(roleQueryWrapper);
        }
        //其余情况先不考虑
        return false;
    }

    /**
     * 从角色list中提取出用于填充组织架构名称相关的map
     *
     * @param roleList
     * @return
     */
    @Override
    public RoleOrgStructureDTO getRoleOrgStructureData(List<Role> roleList) {

        //当前的角色ids 的企业id集合
        HashSet<Integer> entIdSet = new HashSet<>();
        for (Role role : roleList) {
            if (null != role.getEnterpriseId()) {
                entIdSet.add(role.getEnterpriseId());
            }
        }
        //当前的角色ids 的项目id集合
        HashSet<Integer> proIdSet = new HashSet<>();
        for (Role role : roleList) {
            if (null != role.getProjectId()) {
                proIdSet.add(role.getProjectId());
            }
        }
        if (CollectionUtils.isEmpty(entIdSet) && CollectionUtils.isEmpty(proIdSet)) {
            return null;
        }
        List<Integer> entIdList = new ArrayList<>(entIdSet);
        List<Integer> proIdList = new ArrayList<>(proIdSet);
        //处理项目的组织id集合
        OrganizationQuery projectOrganizationQuery = new OrganizationQuery();
        projectOrganizationQuery.withProjectIds(proIdList);
        projectOrganizationQuery.withTypes(Arrays.asList(OrganizationTypeEnum.PROJECT.id.intValue()));
        List<Organization> projectOrganizations = organizationService.list(projectOrganizationQuery);
        if (CollectionUtils.isEmpty(projectOrganizations)) {
            log.warn("当前需要查找的项目集合为={}，但是获取不到相关的组织数据", proIdList.toString());
            throw new DataException("项目集合无对应组织数据");
        }
        Map<Integer, Integer> projectOrganizationMap = new HashMap<>();
        for (Organization organization : projectOrganizations) {
            Integer projectId = organization.getProjectId();
            Integer orgId = organization.getId();
            projectOrganizationMap.put(projectId, orgId);
        }
        List<Integer> projectOrganizationIdList = projectOrganizations.stream().map(e -> e.getId()).collect(Collectors.toList());
        //处理企业的组织id集合
        OrganizationQuery enterpriseOrganizationQuery = new OrganizationQuery();
        enterpriseOrganizationQuery.withEnterpriseIds(entIdList);
        enterpriseOrganizationQuery.withTypes(Arrays.asList(OrganizationTypeEnum.ENTERPRISE.id.intValue()));
        List<Organization> enterpriseOrganizations = organizationService.list(enterpriseOrganizationQuery);
        if (CollectionUtils.isEmpty(enterpriseOrganizations)) {
            log.warn("当前需要查找的企业集合为={}，但是获取不到相关的组织数据", entIdList.toString());
            throw new DataException("企业集合无对应组织数据");
        }
        Map<Integer, Integer> enterpriseOrganizationMap = enterpriseOrganizations.stream().collect(Collectors.toMap(Organization::getEnterpriseId, Organization::getId));
        List<Integer> enterpriseOrganizationIdList = enterpriseOrganizations.stream().map(e -> e.getId()).collect(Collectors.toList());
        List<Integer> organizationIdAll = new ArrayList<>();
        organizationIdAll.addAll(projectOrganizationIdList);
        organizationIdAll.addAll(enterpriseOrganizationIdList);
        //获取组织id链式完整名称的数据map
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withIds(organizationIdAll).withTypes(Arrays.asList(OrganizationTypeEnum.PROJECT.id.intValue(), OrganizationTypeEnum.ENTERPRISE.id.intValue()));
        Map<Integer, String> organizationNameMap = organizationService.batchFullName(organizationQuery);

        RoleOrgStructureDTO roleOrgStructureDTO = new RoleOrgStructureDTO()
                .setEnterpriseOrganizationMap(enterpriseOrganizationMap)
                .setProjectOrganizationMap(projectOrganizationMap)
                .setOrganizationNameMap(organizationNameMap);
        return roleOrgStructureDTO;
    }


    /**
     * 判断该账号是不是超管
     *
     * @param accountId
     * @return
     */
    @Override
    public boolean isSuperManager(Integer accountId) {
        List<Role> list = getRoleListByAccountId(accountId);
        if (list.isEmpty()) {
            log.error("该帐号 {} 没有关联角色信息", accountId);
            return false;
        }
        for (Role r : list) {
            if (r.getType().intValue() == RoleTypeEnum.SUPPER_MANAGER.code) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断该账号是不是企管
     *
     * @param accountId
     * @return
     */
    @Override
    public boolean isEntManager(Integer accountId) {
        List<Role> list = getRoleListByAccountId(accountId);
        if (list.isEmpty()) {
            return false;
        }
        for (Role r : list) {
            if (r.getType().intValue() == RoleTypeEnum.MANAGER.code && r.getGrade().equals(BusinessType.ENTERPRISE.code)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断该账号是不是项管
     *
     * @param accountId
     * @return
     */
    @Override
    public boolean isProjectManager(Integer accountId) {
        List<Role> list = getRoleListByAccountId(accountId);
        if (list.isEmpty()) {
            return false;
        }
        for (Role r : list) {
            if (r.getType().intValue() == RoleTypeEnum.MANAGER.code && r.getGrade().equals(BusinessType.PROJECT.code)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isOperationalManager(Integer accountId) {
        List<Role> list = getRoleListByAccountId(accountId);
        if (list.isEmpty()) {
            return false;
        }
        for (Role r : list) {
            if (r.getType().intValue() == RoleTypeEnum.OPERATE_MANAGER.code) {
                return true;
            }
        }
        return false;
    }

    /**
     * 动态查询封装器生成
     *
     * @param roleQuery
     * @return
     */
    private QueryWrapper<Role> handleParams(RoleQuery roleQuery) {

        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("is_deleted", false);
        if (null == roleQuery) {
            return roleQueryWrapper;
        }
        roleQueryWrapper.orderBy(!org.springframework.util.StringUtils.isEmpty(roleQuery.getOrderColumn()), roleQuery.getOrderAsc(), roleQuery.getOrderColumn());
        if (!CollectionUtils.isEmpty(roleQuery.getSelectColumnList())) {
            String[] fieldNameArray = roleQuery.getSelectColumnList().stream().toArray(String[]::new);
            roleQueryWrapper.select(fieldNameArray);
        }
        if (null != roleQuery.getExcludeId()) {
            roleQueryWrapper.ne("id", roleQuery.getExcludeId());
        }
        if (!CollectionUtils.isEmpty(roleQuery.getExcludeIdList())) {
            roleQueryWrapper.notIn("id", roleQuery.getExcludeIdList());
        }
        if (!CollectionUtils.isEmpty(roleQuery.getIdList())) {
            roleQueryWrapper.in("id", roleQuery.getIdList());
        }
        if (!CollectionUtils.isEmpty(roleQuery.getCodeList())) {
            roleQueryWrapper.in("code", roleQuery.getCodeList());
        }
        if (!CollectionUtils.isEmpty(roleQuery.getIndustryIdList())) {
            roleQueryWrapper.in("industry_id", roleQuery.getIndustryIdList());
        }
        if (null != roleQuery.getParentId()) {
            roleQueryWrapper.eq("parent_id", roleQuery.getParentId());
        }
        if (StringUtils.isNotEmpty(roleQuery.getName())) {
            roleQueryWrapper.eq("name", roleQuery.getName());
        }
        if (StringUtils.isNotEmpty(roleQuery.getCode())) {
            roleQueryWrapper.eq("code", roleQuery.getCode());
        }
        if (null != roleQuery.getType()) {
            roleQueryWrapper.eq("type", roleQuery.getType());
        }
        if(!CollectionUtils.isEmpty(roleQuery.getTypeList())){
            roleQueryWrapper.in("type", roleQuery.getTypeList());
        }
        if (null != roleQuery.getGrade()) {
            roleQueryWrapper.eq("grade", roleQuery.getGrade());
        }
        if (null != roleQuery.getStatus()) {
            roleQueryWrapper.eq("status", roleQuery.getStatus());
        }
        if (!CollectionUtils.isEmpty(roleQuery.getProjectIdList())) {
            roleQueryWrapper.in("project_id", roleQuery.getProjectIdList());
        }
        if (StringUtils.isNotEmpty(roleQuery.getLikeName())) {
            roleQueryWrapper.like("name", roleQuery.getLikeName());
        }
        if (!CollectionUtils.isEmpty(roleQuery.getOrProjectIdList()) || !CollectionUtils.isEmpty(roleQuery.getOrEnterpriseIdList())) {
            roleQueryWrapper.and(
                    wrapper -> wrapper
                            .in(!CollectionUtils.isEmpty(roleQuery.getOrEnterpriseIdList()), "enterprise_id", roleQuery.getOrEnterpriseIdList())
                            .or()
                            .in(!CollectionUtils.isEmpty(roleQuery.getOrProjectIdList()), "project_id", roleQuery.getOrProjectIdList())
            );
        }

        roleQueryWrapper.eq("is_deleted", false);
        //是否查询全局角色
        if (!CollectionUtils.isEmpty(roleQuery.getEnterpriseIdList())) {
            if (null != roleQuery.getIsContainGlobalRole() && roleQuery.getIsContainGlobalRole()) {

                if (!CollectionUtils.isEmpty(roleQuery.getProjectIdList())) {
                    roleQueryWrapper.or(
                            wrapper -> wrapper.in("enterprise_id", roleQuery.getEnterpriseIdList())
                                    .eq("grade", BusinessType.ENTERPRISE.code).eq("is_deleted", false)
                                    //.notIn(!CollectionUtils.isEmpty(roleQuery.getExcludeIdList()), "id", roleQuery.getExcludeIdList())
                    );

                } else {
                    roleQueryWrapper.and(
                            wrapper -> wrapper.in("enterprise_id", roleQuery.getEnterpriseIdList()).
                                    eq("grade", BusinessType.ENTERPRISE.code)
                    );
                }
            } else {
                roleQueryWrapper.in("enterprise_id", roleQuery.getEnterpriseIdList());
            }

        }
        //排除不查询的角色类型
        if (!CollectionUtils.isEmpty(roleQuery.getExcludeType())) {
            roleQueryWrapper.notIn("type", roleQuery.getExcludeType());
        }

        //只需要物业角色
        if (roleQuery.getOnlyNeedRealtyManage()) {
            roleQueryWrapper.notIn("grade", BusinessType.INDUSTRY.code);
        }

        //普通内置角色获取
        if (!CollectionUtils.isEmpty(roleQuery.getCommonInitialized())) {
            roleQueryWrapper.or(
                    wrapper -> wrapper.in("id", roleQuery.getCommonInitialized())
                            .eq("is_deleted", false)
            );
        }
        if (null != roleQuery.getIsInitialized()) {
            roleQueryWrapper.eq("is_initialized", roleQuery.getIsInitialized());
        }
        if (StringUtils.isNotEmpty(roleQuery.getAppId())) {
            App app = appService.getByAppId(roleQuery.getAppId());
            if (null != app) {
                roleQueryWrapper.eq("app_id", app.getId());
            }
        }
        // 角色不属于某个业态 industry_id目前只表示角色是在哪创建的
//        if(null != roleQuery.getDevelopId()){
//            QueryWrapper<Industry> industryQueryWrapper = new QueryWrapper<>();
//            industryQueryWrapper.select("id");
//            industryQueryWrapper.eq("develop_id", roleQuery.getDevelopId());
//            List<Industry> list = industryService.list(industryQueryWrapper);
//            if(!list.isEmpty()){
//                roleQueryWrapper.in("industry_id", list.stream().map(i -> i.getId()).collect(Collectors.toList()));
//            }
//        }
        return roleQueryWrapper;
    }

    /**
     * 获取当前业态下普通内置角色 下拉选择器
     *
     * @param industryId
     * @return
     */
    @Override
    public List<Map<String, Object>> getCommonInitRoleEnumList(Short industryId) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (InitializeRoleEnum initializeRoleEnum : InitializeRoleEnum.values()) {
            Map<String, Object> map = new HashMap<>();
            if (industryId == initializeRoleEnum.getIndustryId()) {
                map.put("id", initializeRoleEnum.getId());
                map.put("enumName", initializeRoleEnum.name());
                map.put("roleName", initializeRoleEnum.getName());
                list.add(map);
            }

        }
        return list;
    }


    public void dealContainProRelationRoles(RoleQuery roleQuery) {
        if (!CollectionUtils.isEmpty(roleQuery.getContainEntRoleProIds())) {
            List<Integer> proIds = roleQuery.getContainEntRoleProIds();
            ProjectQuery projectQuery = new ProjectQuery();
            projectQuery.withIdList(proIds);
            List<Project> projectList = projectService.list(projectQuery, null);
            if (CollectionUtils.isEmpty(projectList)) {
                log.info("项目数据异常，数据库内查找为空,projectList={}", projectList);
                throw new DataException("项目数据异常");
            }
            Set<Integer> enterpriseIdSet = projectList.stream().map(Project::getEnterpriseId).collect(Collectors.toSet());
            roleQuery.setContainEntRoleEntIds(new ArrayList<>(enterpriseIdSet));
        }
    }

    @Override
    public List<Role> getList(RoleQuery roleQuery) {
        if (null != roleQuery) {
            //设置权限码相关角色
            dealPermissionCodes(roleQuery);
            //设置业务关联的项目数据
            dealContainProRelationRoles(roleQuery);
            //设置是否获取普通内置角色
            dealCommonInitRole(roleQuery);
            //设置是否获取超管角色
            dealSuperAdmin(roleQuery);
        }
        return roleDao.getList(roleQuery);
    }

    @Override
    public Page<Role> getPageList(Account operateAccount, Page page, RoleQuery roleQuery) {
        if (null != roleQuery) {
            //设置是否获取普通内置角色
            dealCommonInitRole(roleQuery);
            //设置是否获取超管角色
            dealSuperAdmin(roleQuery);
            //设置权限码相关角色
            dealPermissionCodes(roleQuery);
            //设置业务关联的项目数据
            dealContainProRelationRoles(roleQuery);
        }
        //处理关于权限的数据过滤
        roleQuery = handleRequest(operateAccount, roleQuery);
        return roleDao.getPageList(page, roleQuery);
    }

    @Override
    public List<Role> getTouristRoleByIndustryId(Short industryId) {
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setIndustryIdList(Collections.singletonList(industryId));
        roleQuery.setType(RoleTypeEnum.TOURIST.code);
        return getRoleList(null, roleQuery);
    }

    @Override
    public ResultJson updateRoleAdminV2(RoleGrantDTO roleGrantDTO, AdminAccount adminAccount) {
        Role role1 = new Role();
        BeanUtils.copyProperties(roleGrantDTO, role1);
        String appId = roleGrantDTO.getAppId();
        App app = appService.getByAppId(appId);
        if (null == app) {
            return ResultJson.fail("不存在的应用");
        }
        if (roleExistChecking(roleGrantDTO)) {
            return ResultJson.fail("角色重复");
        }
        role1.setAppId(app.getId());
        updateById(role1);
        List<Integer> permissionIds = roleGrantDTO.getPermissionIds();
        if (!CollectionUtils.isEmpty(permissionIds)) {
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.select("id");
            permissionQueryWrapper.in("id", permissionIds);
            List<Permission> permissions = permissionDao.selectList(permissionQueryWrapper);
            // 先删除再新增
            QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
            rolePermissionQueryWrapper.eq("role_id", role1.getId());
            rolePermissionService.remove(rolePermissionQueryWrapper);
            if (!CollectionUtils.isEmpty(permissions)) {
                rolePermissionService.createRolePermission(roleGrantDTO.getId(), permissions.stream().map(i -> i.getId()).collect(Collectors.toList()));
            }
        }
        //创建场景关联
        createRoleScene(roleGrantDTO.getId(),roleGrantDTO.getSceneIds());
        //刷新权限缓存
        permissionAuthService.refreshAppAuth(app.getId().toString());
        return ResultJson.success();
    }

    /**
     * 创建角色场景关系
     */
    private void createRoleScene(Integer roleId,List<Integer> sceneIds){
        if(CollectionUtils.isEmpty(sceneIds) || roleId == null){
            return;
        }
        //先删除
        QueryWrapper<SceneRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        sceneRoleDao.delete(queryWrapper);
        //在增加
        SceneRole sceneRole = null;
        for(Integer id:sceneIds){
            sceneRole = new SceneRole();
            sceneRole.setRoleId(roleId);
            sceneRole.setSceneId(id);
            sceneRoleDao.insert(sceneRole);
        }
    }

    @Override
    public Map<Integer, List<Role>> batchRoleMap(List<Integer> accountIds) {

        if (CollectionUtils.isEmpty(accountIds)) {
            return Collections.emptyMap();
        }
        QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
        accountRoleQueryWrapper.in("account_id", accountIds);
        List<AccountRole> accountRoles = accountRoleService.list(accountRoleQueryWrapper);
        if (accountRoles.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<Integer, List<Integer>> accountRoleMap = accountRoles.stream().collect(Collectors.groupingBy(AccountRole::getAccountId, Collectors.mapping(AccountRole::getRoleId, Collectors.toList())));
        List<Integer> roleIds = accountRoles.stream().map(i -> i.getRoleId()).distinct().collect(Collectors.toList());
        List<Role> roles = roleDao.selectBatchIds(roleIds);
        if (CollectionUtils.isEmpty(roles)) {
            return Collections.emptyMap();
        }
        Map<Integer, Role> roleMap = roles.stream().collect(Collectors.toMap(Role::getId, Function.identity()));
        Map<Integer, List<Role>> result = new HashMap<>();
        for (Map.Entry<Integer, List<Integer>> en : accountRoleMap.entrySet()) {
            List<Integer> roleIds1 = en.getValue();
            List<Role> r = new ArrayList<>();
            if (!CollectionUtils.isEmpty(roleIds1)) {
                for (Integer integer : roleIds1) {
                    r.add(roleMap.get(integer));
                }
            }
            result.put(en.getKey(), r);
        }
        return result;
    }

    /**
     * 处理 设置是否获取普通内置角色
     *
     * @param roleQuery
     */
    public void dealCommonInitRole(RoleQuery roleQuery) {
        if (null != roleQuery.getNeedCommonInitialized()) {
            List<Integer> commonInitializedRoles = getCommonInitializedRoles(roleQuery.getIndustryIdList());
            if (roleQuery.getNeedCommonInitialized()) {
                roleQuery.setOrCommonInitRoleIds(commonInitializedRoles);
//                if (CollectionUtils.isEmpty(roleQuery.getIdList())) {
//                    roleQuery.setIdList(commonInitializedRoles);
//                } else {
//                    List<Integer> idList = roleQuery.getIdList();
//                    idList.addAll(commonInitializedRoles);
//                    roleQuery.setIdList(idList);
//                }
            } else {
                if (CollectionUtils.isEmpty(roleQuery.getExcludeIdList())) {
                    roleQuery.setExcludeIdList(commonInitializedRoles);
                } else {
                    List<Integer> excludeIdList = roleQuery.getExcludeIdList();
                    excludeIdList.addAll(commonInitializedRoles);
                    roleQuery.setExcludeIdList(excludeIdList);
                }
            }

        }
    }

    /**
     * 处理 设置是否获取超管角色
     *
     * @param roleQuery
     */
    public void dealSuperAdmin(RoleQuery roleQuery) {
        if (null != roleQuery.getNeedSuperAdmin()) {
            if (roleQuery.getNeedSuperAdmin()) {
                List<Integer> superAdminRoles = getSuperAdminRoles(roleQuery.getIndustryIdList());
                roleQuery.setOrSuperAdminRoleIds(superAdminRoles);
//                if (CollectionUtils.isEmpty(roleQuery.getIdList())) {
//                    roleQuery.setIdList(superAdminRoles);
//                } else {
//                    List<Integer> idList = roleQuery.getIdList();
//                    idList.addAll(superAdminRoles);
//                    roleQuery.setIdList(idList);
//                }
            }
        }
    }

    /**
     * 根据角色id列表，筛选出当前的最高角色身份
     *
     * @param roleIdList
     * @return
     */
    public RoleTypeDTO getRoleTypeDTO(List<Integer> roleIdList) {
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setIdList(roleIdList);
        List<Integer> commonInitializedRoles = getCommonInitializedRoles(null);
        for (Integer roleId : commonInitializedRoles) {
            if (roleIdList.contains(roleId)) {
                roleQuery.setNeedCommonInitialized(true);
            }
        }
        List<Role> roleList = getRoleList(null, roleQuery);
        if (CollectionUtils.isEmpty(roleList)) {
            //其他
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.OTHERS);
            return roleTypeDTO;
        }
        List<Role> superManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.SUPPER_MANAGER.code)).collect(Collectors.toList());
        //超级管理员
        if (!CollectionUtils.isEmpty(superManageList)) {
            List<Short> industryIdList = superManageList.stream().map(e -> e.getIndustryId()).collect(Collectors.toList());
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.SUPPER_MANAGER);
            roleTypeDTO.setIndustryIdList(industryIdList);
            return roleTypeDTO;
        }
        //运维管理员
        //List<Role> operateManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.OPERATE_MANAGER.code)).collect(Collectors.toList());
        List<Role> entManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.MANAGER.code)
                && role.getGrade().equals(BusinessType.ENTERPRISE.code)).collect(Collectors.toList());
        //企业管理员
        if (!CollectionUtils.isEmpty(entManageList)) {
            List<Integer> entIds = entManageList.stream().map(e -> e.getEnterpriseId()).collect(Collectors.toList());
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.ENT_MANAGER);
            roleTypeDTO.setEnterpriseIdList(entIds);
            return roleTypeDTO;
        }
        List<Role> proManageList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.MANAGER.code)
                && role.getGrade().equals(BusinessType.PROJECT.code)).collect(Collectors.toList());
        //项目管理员
        if (!CollectionUtils.isEmpty(proManageList)) {
            List<Integer> proIdList = proManageList.stream().map(r -> r.getProjectId()).collect(Collectors.toList());
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.PRO_MANAGER);
            roleTypeDTO.setProjectIdList(proIdList);
            return roleTypeDTO;
        }
        List<Role> commonList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.COMMON.code)).collect(Collectors.toList());
        //普通
        if (!CollectionUtils.isEmpty(commonList)) {
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.COMMON);
            return roleTypeDTO;
        }
        List<Role> guestList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.GUEST.code)).collect(Collectors.toList());
        //访客
        if (!CollectionUtils.isEmpty(guestList)) {
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.GUEST);
            return roleTypeDTO;
        }
        List<Role> touristList = roleList.stream().filter(role -> role.getType().equals(RoleTypeEnum.TOURIST.code)).collect(Collectors.toList());
        //游客
        if (!CollectionUtils.isEmpty(touristList)) {
            RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
            roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.TOURIST);
            return roleTypeDTO;
        }
        //其他
        RoleTypeDTO roleTypeDTO = new RoleTypeDTO();
        roleTypeDTO.setRoleTypeEnum(RoleTypeEnum.OTHERS);
        return roleTypeDTO;
    }

    /**
     * 操作日志记录
     *
     * @param operateAccount
     * @param logOperationTypeEnum
     * @param operateContent
     * @param roleGrantDTO
     */
    public void roleLogRecord(AbstractAccount operateAccount, LogOperationTypeEnum logOperationTypeEnum, String operateContent, RoleGrantDTO roleGrantDTO) {
        OperateLog operateLog = new OperateLog();
        operateLog.setMenu(ModuleTypeEnum.ROLE_MANAGE.getName());
        operateLog.setOperateType(logOperationTypeEnum.getType());
        operateLog.setOperateContent(operateContent);
        operateLog.setEnterpriseId(roleGrantDTO.getEnterpriseId());
        if (null != roleGrantDTO.getProjectId()) {
            Project project = projectService.findById(roleGrantDTO.getProjectId());
            operateLog.setProjectId(project.getId());
            operateLog.setProjectName(project.getName());
        }
        operateLog.setIp(ThreadLocalUtil.getIp());
        operateLog.setIndustryId(ThreadLocalUtil.getIndustryId());
        if (null == operateAccount) {
            operateAccount = ThreadLocalUtil.getAccount();
        }
        if (null != operateAccount) {
            operateLog.setIndustryId(operateAccount.getIndustryId());
            operateLog.setAccountId(operateAccount.getId());
            operateLog.setLoginName(operateAccount.getLoginName());
            operateLog.setName(operateAccount.getName());
            //填充企业ids+项目ids
            Account account = new Account();
            BeanUtils.copyProperties(operateAccount,account);
            List<Enterprise> enterprises = enterpriseService.list(null,account);
            if (!CollectionUtils.isEmpty(enterprises)){
                operateLog.setEnterpriseIds(enterprises.stream().map(Enterprise::getId).collect(Collectors.toList()));
            }
            List<AccountDetailDTO> projectInfoList = accountService.getAccountProjectInfoByIdList(Collections.singletonList(operateAccount.getId()));
            if (!CollectionUtils.isEmpty(projectInfoList)){
                operateLog.setProjectIds(projectInfoList.stream().map(AccountDetailDTO::getProjectId).collect(Collectors.toList()));
            }
        }
        logTemplate.addOperateLog(operateLog);
    }
}
